package org.test.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 单词转换，注意所有文件都要GBK
 * 
 * @author xgj
 * 
 */
@SuppressWarnings("unchecked")
public class OrderWord {
    private static final String CHARSET = "UTF-8";
    private static String INPUT_FILE = "D:/单词.xml";
    private static String OUTPUT_FILE = "D:/转换后的单词.txt";
    /**
     * 以前导出的数据，
     */
    private static String OLD_WORD_FILE = "D:/以前的单词.txt";

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(INPUT_FILE), CHARSET));
        SAXReader reader = new SAXReader(false);
        reader.setEncoding(CHARSET);
        Document doc = reader.read(new File(INPUT_FILE));
        Element rootEle = doc.getRootElement();
        List<Element> items = rootEle.elements("item");
        TreeSet<Word> wordSet = new TreeSet<OrderWord.Word>();
        for (Element item : items) {
            String name = item.element("word").getTextTrim();
            String trans = item.element("trans").getTextTrim();
            trans = trans.replaceAll("\\n\\s*", "");
            String phonetic = item.element("phonetic").getTextTrim();
            phonetic = phonetic.replaceAll("\\n\\s*", "");
            Word word = new OrderWord.Word();
            word.setName(name);
            word.setTrans(trans);
            word.setPhonetic(phonetic);
            wordSet.add(word);
        }
        /**
         * 如果要剔除以前老的单词，就调用wipteWord
         */
        wipeWord(wordSet);
        writeToFile(wordSet);
        br.close();
    }

    /**
     * 去除老的单词
     */
    private static void wipeWord(Collection<Word> wordSet) throws Exception {
        System.out.println("------>剔除单词开始");
        Pattern oldWordIdRegex = Pattern.compile("^\\d+，([-\\w\\s']+)((\\[.+\\])*)$");
        Matcher matcher = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(OLD_WORD_FILE), CHARSET));
        String line = null;
        while ((line = removeUtfBom(br.readLine())) != null) {
            matcher = oldWordIdRegex.matcher(line);
            if (matcher.matches()) {
//                System.out.println(matcher.groupCount());
//                for (int i = 0; i < matcher.groupCount(); i++) {
//                    System.out.println(matcher.group(i));
//                }
                wordSet.remove(new Word(matcher.group(1)));

            }
        }
        br.close();
        System.out.println("剔除单词完成<------");
    }

    /**
     * 转
     * 
     * @param depaName
     * @return
     * @throws Exception
     */
    private static String removeUtfBom(String depaName) throws Exception {
        if (depaName == null) {
            return null;
        } else {
            byte[] bytes = depaName.getBytes();
            if (bytes.length >= 3) {
                byte b1 = bytes[0];
                byte b2 = bytes[1];
                byte b3 = bytes[2];
                if (b1 == (byte) 0XEF && b2 == (byte) 0XBB && b3 == (byte) 0XBF) {
                    return new String(bytes, 3, bytes.length - 3, "UTF-8");
                } else {
                    return depaName;
                }
            } else {
                return depaName;
            }
        }
    }

    /**
     * 写到文件
     * 
     * @param set
     * @throws Exception
     */
    private static void writeToFile(Collection<Word> set) throws Exception {
        System.out.println("------>写入文件开始");
        BufferedWriter bw = new BufferedWriter(new FileWriter(OUTPUT_FILE));
        int i = 1;
        for (Word word : set) {
            bw.write(i + "，" + word.getName() + word.getPhonetic() + "\n");
            bw.write(word.getTrans() + "\n");
            bw.newLine();
            bw.newLine();
            i++;
        }
        bw.close();
        System.out.println("写入文件完成<------");
    }

    /**
     * 单词类
     * 
     * @author xgj
     * 
     */
    private static class Word implements Comparable<Word> {
        /**
         * 名字
         */
        private String name;

        public Word(String name){
            super();
            this.name = name;
        }

        /**
         * 翻译
         */
        private String trans;
        /**
         * 发音
         */
        private String phonetic;

        public String getPhonetic() {
            return phonetic;
        }

        public void setPhonetic(String phonetic) {
            this.phonetic = phonetic;
        }

        public Word(){
            // TODO Auto-generated constructor stub 
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getTrans() {
            return trans;
        }

        public void setTrans(String trans) {
            this.trans = trans;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Word other = (Word) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

        @Override
        public int compareTo(Word o) {
            return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
        }

    }

}
